import 'package:base_lib/app.dart';
import 'package:base_lib/common/bus/bus.dart';
import 'package:base_lib/common/bus/ibus.dart';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/config.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/index.dart';
import 'package:base_lib/utils/shared_preference_util.dart';
import 'package:doctor_login_lib/audit/auditingPage.dart';
import 'package:doctor_login_lib/audit/rejectAuditPage.dart';
import 'package:doctor_login_lib/brief_desc/page.dart';
import 'package:doctor_login_lib/certification/page.dart';
import 'package:doctor_login_lib/disease/page.dart';
import 'package:doctor_login_lib/events.dart';
import 'package:doctor_login_lib/forgot_password/page.dart';
import 'package:doctor_login_lib/good_at/page.dart';
import 'package:doctor_login_lib/register_phone/page.dart';
import 'package:doctor_login_lib/repository/http.dart';
import 'package:doctor_login_lib/select_section/page.dart';
import 'package:doctor_login_lib/set_login_password/page.dart';
import 'package:doctor_login_lib/set_user_info/page.dart';
import 'package:flutter/cupertino.dart';
import 'cache/userinfo_cache.dart';
import 'login/page.dart';
import 'login/entity/doctor_login_entity.dart' as LoginBean;
import 'login/entity/doctor_review_status_entity.dart' as ReviewBean;

class DoctorLoginComponent extends IComponent {
  static const String AssetsPackageName = "doctor_login_lib";

  static const String KEY_TOKEN = 'token';

  static const String KEY_PHONE = 'phone';

  static const String KEY_PWD = 'pwd';

  static void dealLoginLogic(BuildContext context, LoginBean.Data data,
      {bool isLoginByCode = false}) async {
    UserInfoCache.getInstance().cacheData(data.doctorUser);
    SPUtil.putString("token", data.token);

    if (isLoginByCode && data.setPersonPass != "0") {
      Routers.navigateTo(context, setLoginPasswordPage,
          parameters: Parameters()..putString("phone", data.doctorUser.phone));
      return;
    }

    String path;
    Parameters parameters;
    bool clear = false;

    if (data.doctorUser.doctorTypeID == 0) {
      //未填写医生信息，跳转到填写信息页面
      path = setDoctorInfoPage;
    } else if (data.doctorUser.doctorTypeID == 1) {
      //医生
      ResultBody<ReviewBean.Data> reviewData =
          await LoginHttp.getDoctorReviewStatus(data.doctorUser.keyID);
      if (reviewData.isSuccess) {
        switch (reviewData.data.auditStatusID) {
          case 0: //去完善个人信息
            path = setDoctorInfoPage;
            break;

          case 1: //实名认证审核中，跳转到审核中页面
            path = auditingPage;
            break;

          case 2: //实名认证审核成功，跳转到主页
            EventBus.instance.post(context, loginPage, null);
            path = Routers.main_page;
            clear = true;
            break;

          default: //实名认证审核失败，跳转到审核失败页面
            path = rejectAuditPage;
            parameters = Parameters()..putObj("doctor", reviewData.data);
            break;
        }
      } else {
        ToastUtil.info(reviewData.error.msg);
      }
    } else {
      ToastUtil.info(data.doctorUser.auditStatusName);
    }
    if (path != null)
      Routers.navigateTo(context, path,
          parameters: parameters, clearStack: clear);
  }

  static String registerPhonePage = AssetsPackageName + "/registerPhone";

  static String loginPage = AssetsPackageName + "/login";

  static String forgotPwdPage = AssetsPackageName + "/forgotPwd";

  static String setLoginPasswordPage = AssetsPackageName + "/setLoginPassword";

  static String setDoctorInfoPage = AssetsPackageName + "/setUserInfo";

  ///选择科室
  static String selectSectionPage = AssetsPackageName + "/selectSection";

  ///专治疾病
  static String diseasePage = AssetsPackageName + "/disease";

  ///擅长
  static String goodAtPage = AssetsPackageName + "/goodAt";

  ///简介
  static String briefDescPage = AssetsPackageName + "/briefDesc";

  ///实名认证
  static String certificationPage = AssetsPackageName + "/certification";

  ///审核中
  static String auditingPage = AssetsPackageName + "/auditing";

  ///审核失败
  static String rejectAuditPage = AssetsPackageName + "/rejectAudit";

  @override
  getComponentName() {
    return AssetsPackageName;
  }

  @override
  void doComponentInitConfig() async {
    //       buildConfigField "String", "API_PATH", "\"https://doctorlogin-cs.jk.100cbc.com\""
    // //            buildConfigField "String", "LOGIN_PATH", "\"http://10.0.0.211:6108\""
    // //            buildConfigField "String", "DOCTOR_PATH","\"http://10.0.0.211:6110\""
    // //            buildConfigField "String", "RP_PATH","\"http://10.0.0.211:6111\""
    // //            buildConfigField "String", "FILE_PATH","\"http://10.0.0.211:6104\""
    LoginHttp.createHttpProxy(mBaseUrl: Config.loginBaseUrl);
    await SPUtil.getInstance();
  }

  ///获取页面配置信息
  @override
  List<PageBuilder> getPages() {
    return [
      PageBuilder(loginPage, (parameters) {
        return LoginPage(parameters);
      }),
      PageBuilder(forgotPwdPage, (parameters) {
        return ForgotPasswordPage(parameters);
      }),
      PageBuilder(registerPhonePage, (parameters) {
        return RegisterPhonePage(parameters);
      }),
      PageBuilder(setLoginPasswordPage, (parameters) {
        return SetLoginPasswordPage(parameters);
      }),
      PageBuilder(setDoctorInfoPage, (parameters) {
        return SetUserInfoPage(parameters);
      }),
      PageBuilder(auditingPage, (parameters) {
        return AuditingPage();
      }),
      PageBuilder(rejectAuditPage, (parameters) {
        return RejectAuditPage(parameters);
      }),
      PageBuilder(selectSectionPage, (parameters) {
        return SelectSectionPage(parameters);
      }),
      PageBuilder(diseasePage, (parameters) {
        return DiseasePage(parameters);
      }),
      PageBuilder(goodAtPage, (parameters) {
        return GoodAtPage(parameters);
      }),
      PageBuilder(briefDescPage, (parameters) {
        return BriefDescPage(parameters);
      }),
      PageBuilder(certificationPage, (parameters) {
        return CertificationPage(parameters);
      }),
    ];
  }

  ///获取主动暴露给外部的事件列表
  @override
  List<EventBuilder> gePublicEvents() => [
        //判断是否需要重新登录
        EventBuilder(
            componentName, "DetermineWhetherNeed2LoginAgain", jump2Login),
      ];

  ///自动登录
  static void doAutoLogin(BuildContext context) async {
    var jump2Login = () {
      Routers.navigateTo(context, Routers.login_page, clearStack: true);
    };

    var token = SPUtil.getString('token');
    if (token.isEmpty) {
      Routers.navigateTo(context, Routers.login_page, clearStack: true);
    } else {
      var result = await LoginHttp.validateDoctorToken(token);
      if (!result.isSuccess) {
        String phone = SPUtil.getString('phone', defValue: '');
        String pwd = SPUtil.getString('pwd', defValue: '');
        if (phone.isNotEmpty && pwd.isNotEmpty) {
          var loginResult = await LoginHttp.doctorLogin(phone, pwd);
          if (loginResult.isSuccess) {
            if (loginResult?.data?.doctorUser != null)
              dealLoginLogic(context, loginResult.data);
            else
              jump2Login();
          } else {
            jump2Login();
          }
        } else {
          jump2Login();
        }
      } else {
        Routers.navigateTo(context, Routers.main_page, clearStack: true);
      }
    }
  }
}
